package com.acwing.partition12;

import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * @author `RKC`
 * @date 2022/2/28 16:15
 */
public class AC1101献给阿尔吉侬的花束_aStar {

    private static final int N = 210;
    private static final int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private static char[][] g = new char[N][N];
    private static int[][] dist = new int[N][N];
    private static PriorityQueue<Node> heap = new PriorityQueue<>(N * N);
    private static int n, m;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        int t = Integer.parseInt(reader.readLine());
        while (t-- > 0) {
            String[] ss = reader.readLine().split(" ");
            n = Integer.parseInt(ss[0]);
            m = Integer.parseInt(ss[1]);
            int[] start = null, end = null;
            for (int i = 0; i < n; i++) {
                String s = reader.readLine();
                for (int j = 0; j < m; j++) {
                    g[i][j] = s.charAt(j);
                    if (g[i][j] == 'S') start = new int[]{i, j};
                    else if (g[i][j] == 'E') end = new int[]{i, j};
                }
            }
            int ans = aStar(start, end);
            if (ans == -1) writer.write("oop!\n");
            else writer.write(ans + "\n");
        }
        writer.flush();
    }

    private static int aStar(int[] start, int[] end) {
        if (start[0] == end[0] && start[1] == end[1]) return 0;
        heap.clear();
        for (int i = 0; i < N; i++) Arrays.fill(dist[i], 0);
        heap.add(new Node(start[0], start[1], eval(start[0], start[1], end[0], end[1])));
        while (!heap.isEmpty()) {
            Node cur = heap.poll();
            int x = cur.x, y = cur.y;
            if (x == end[0] && y == end[1]) return dist[x][y];
            for (int[] dir : dirs) {
                int nx = x + dir[0], ny = y + dir[1];
                if (nx < 0 || nx >= n || ny < 0 || ny >= m || g[nx][ny] == '#') continue;
                if (dist[nx][ny] == 0 || dist[nx][ny] > dist[x][y] + 1) {
                    dist[nx][ny] = dist[x][y] + 1;
                    heap.add(new Node(nx, ny, dist[x][y] + 1 + eval(nx, ny, end[0], end[1])));
                }
            }
        }
        return -1;
    }

    private static int eval(int x1, int y1, int x2, int y2) {
        //估价函数是当前位置到目的位置的一个曼哈顿距离
        return Math.abs(x1 - x2) + Math.abs(y1 - y2);
    }

    private static class Node implements Comparable<Node> {
        private int x, y, est;

        public Node(int x, int y, int est) {
            this.x = x;
            this.y = y;
            this.est = est;
        }

        @Override
        public int compareTo(Node o) {
            return est - o.est;
        }
    }
}
